<template>
  <div class="box">
    <!-- 商品项 -->
    <div class="item" v-for="item in cartStore.cartList" :key="item.id">
      <input type="checkbox" />
      <img :src="item.picUrl" />
      <div class="desc">
        <i>{{ item.goodsName }}</i>
        <p>
          <span id="desc">{{ item.specifications[0] }}</span>
          <span id="desc" v-if="item.specifications[1]">{{
            item.specifications[1]
          }}</span>
        </p>
        <i>¥{{ item.price.toFixed(2) }}</i>
        <i>×{{ item.number }}</i>
        <div>
          <button @click="handleDecrement(item)" :disabled="item.number <= 1">
            -
          </button>
          <input
            v-model.number="item.number"
            id="num"
            type="number"
            @change="handleInputChange(item, $event)"
          />
          <button @click="handleIncrement(item)">+</button>
        </div>
      </div>
      <p id="del" @click="handleDel(item.productId)">删除</p>
    </div>

    <!-- 底部栏 -->
    <div class="bottom">
      <div>
        <input type="checkbox" />
        <span>全选</span>
      </div>
      <div>
        <i>总计{{ 0 }}</i>
        <button id="buy">结算</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useCartStore } from '@/stores/cart'

const cartStore = useCartStore()

// 减少数量
const handleDecrement = (item) => {
  if (item.number <= 1) return
  cartStore.updateCount(item, item.number - 1)
}

// 增加数量
const handleIncrement = (item) => {
  cartStore.updateCount(item, item.number + 1)
}

// 输入框变化处理
const handleInputChange = (item, e) => {
  let value = parseInt(e.target.value)
  if (isNaN(value) || value < 1) {
    value = 1
    showToast('数量不能小于1')
  }
  cartStore.updateCount(item, value)
}

//删除商品
const handleDel = (productId) => {
  cartStore.deleteGoods(productId)
}
</script>

<style scoped>
.box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.item {
  width: 90%;
  display: flex;
  margin: 10px auto;
  justify-content: center;
  align-items: center;
  border: 1px solid #ececec;
}
img {
  width: 20%;
}
.desc {
  display: flex;
  flex-direction: column;
}
#num {
  width: 10%;
}
p span:first-child {
  margin-right: 15px;
}
#desc {
  border: 1px solid #b1b1b1;
  font-size: 15px;
  padding: 3px;
}
#del {
  padding: 10px;
  white-space: nowrap;
  background-color: red;
  color: white;
}
.bottom {
  width: 90%;
  margin: auto;
  display: flex;
  justify-content: space-between;
}
i {
  margin-right: 10px;
}
#buy {
  padding: 5px 15px;
  border: 0;
  background-color: rgb(255, 69, 69);
  color: white;
}
</style>
